package net.sky.oa.dao.post.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;
import net.sky.oa.dao.SkyBaseDaoImpl;
import net.sky.oa.dao.post.ReplyPostDao;
import net.sky.oa.model.ReplyPost;

@SuppressWarnings("unchecked")
@Repository
public class ReplyPostDaoImpl extends SkyBaseDaoImpl<ReplyPost> implements ReplyPostDao{
    
	public ReplyPostDaoImpl(){
		super.setPersistType(ReplyPost.class);
	}

	public List<ReplyPost> findAllReplyPost() {
        String hql="from ReplyPost rp";		
		return findByHql(hql);
	}
	
	/*
	 *根据当前贴子删除所有贴子回复
	 */
	@SuppressWarnings("unused")
	public void deleteAllReply(Long pid){
		Session session=this.getHibernateTemplate().getSessionFactory().openSession();
		Transaction trans=session.beginTransaction();
		try { 
			
			String hql="delete from ReplyPost rp where rp.sendpost.id="+pid+"";
			Query queryUpdate=this.getSession().createQuery(hql);
			int  intReply=queryUpdate.executeUpdate();
			trans.commit();
		}catch (Exception e) {
			if(trans!=null){
				trans.rollback();
			}
		}finally{
	        session.close();
		}
		
	}
	public Map QueryReplies(final Long rid,final int currentPage,final int lineSize) {
		Map map=new HashMap();
	    List list=getHibernateTemplate().executeFind(new HibernateCallback(){

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				StringBuffer buffer=new StringBuffer("from ReplyPost rp where 1=1 ");
				StringBuffer cbuffer=new StringBuffer("select count(rp.id) from ReplyPost rp where 1=1");
				String hql="";
				if(rid!=-1){
					hql=" and rp.sendpost.id="+rid;
					buffer.append(hql);
					cbuffer.append(hql);
				}
				 buffer.append(" order by rp.createtime asc");
				 List resultList = new ArrayList();
				 Long count = (long)0;
				 Query query = session.createQuery(buffer.toString());
				 if(currentPage!=-1&&lineSize!=-1) {
			     count =(Long)session.createQuery(cbuffer.toString()).uniqueResult();
			     resultList = query.setFirstResult((currentPage - 1) * lineSize)
					.setMaxResults(lineSize).list();
				 }else {
						resultList = query.list();
				 }
				    List list = new ArrayList();
					list.add(count);
					list.add(resultList);				
				    return list;
			}
	    });
	            map.put("count",list.get(0) );
	            map.put("list", list.get(1) );
		        return map;
	}

}
